package com.zhiyin.game.utils;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTemplateUtils {
    private static StringRedisTemplate strRedisTemplate;
    private static HashOperations hashOperations;
    private static SetOperations setOperations;

    public RedisTemplateUtils(StringRedisTemplate redisTemplate) {
        this.strRedisTemplate = redisTemplate;
        hashOperations = this.strRedisTemplate.opsForHash();
        setOperations = this.strRedisTemplate.opsForSet();
    }

    public static SetOperations getSetOperations() {
        return setOperations;
    }

    public static void setHash(String key, Map<String, ?> value) {
        hashOperations.putAll(key, value);
    }

    public static Set getHashFields(String key) {
        return hashOperations.keys(key);
    }

    public static Map getHashEntries(String key) {
        return hashOperations.entries(key);
    }

    public static void putHashValue(String key, String field, Object value) {
        hashOperations.put(key, field, value);
    }

    public static Object getHashValue(String key, String field) {
        return hashOperations.get(key, field);
    }

    public static long incHashKey(String key, String field, long delta) {
        return hashOperations.increment(key, field, delta);
    }

    public static boolean existKey(String key) {
        return strRedisTemplate.hasKey(key);
    }

    public static boolean existHashKey(String key, String field) {
        return hashOperations.hasKey(key, field);
    }

    public static Object getHash(String key) {
        return strRedisTemplate.opsForHash().entries(key);
    }

    public static void delete(String key) {
        strRedisTemplate.delete(key);
    }

    public static void deleteHashKey(String key, String field) {
        strRedisTemplate.opsForHash().delete(key, field);
    }

    public static boolean expire(String key, long timeout, TimeUnit unit) {
        return strRedisTemplate.expire(key, timeout, unit);
    }
}
